package com.hugang.juc.reference;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author hg
 * @date 2020/8/26 16:01
 */
public class WeakHashMapDemo {

    public static void main(String[] args) {
        myHashMap();
        System.out.println("================");
        myWeakHashMap();
    }

    public static void myHashMap(){
        Map<String, String> map = new HashMap<>();
        String key = new String("1");
        String value = "hashmap";
        map.put(key,value);

        System.out.println(map);

        key = null;
        System.out.println(map);

        System.gc();
        System.out.println(map);
    }

    /**
     * 当WeakHashMap的key置为null时，gc才会回收此key所在的entry对象。
     *
     */
    public static void myWeakHashMap(){
        Map<String, String> map = new WeakHashMap<>();
        String key = new String("2");
        String value = "weakhashmap";
        map.put(key,value);

        System.out.println(map);
        //try {
        //    byte[] bytes = new byte[10 * 1024 * 1024];
        //} catch (Throwable e){
        //    e.printStackTrace();
        //} finally {
        //    System.out.println(map);
        //}

        key = null;
        System.out.println(map);

        System.gc();
        System.out.println(map);
    }
}
